﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Oplaco.Core.DAL;
using System.Data;
using Oplaco.Core.BusinessLogicLayer;

namespace Oplaco.Web.DTO
{
    public class LocationManager
    {
        internal const string AllLocationsKey = "LocationCache_AllLocationsKey";
        
        
        public CachedLocationCollection Fetch(HttpContext context, int max)
        {
            DateTime expiration = DateTime.Now.AddDays(1);
            CachedLocationCollection coll = context.Cache[AllLocationsKey] as CachedLocationCollection;
            if (coll == null)
            {
                LocationsDataComponent.LocationsDataTable locationsResult = LocationsDB.GetAllLocations();
                CachedLocation[] arr = (from DataRow row in locationsResult.Rows select new CachedLocation((int)row["Id"], row["Name"].ToString())).ToArray<CachedLocation>();

                if (arr != null && arr.Count() > 0) {
                    coll.CopyTo(arr, 0);
                    context.Cache.Add(AllLocationsKey, coll, null, expiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                }
                
            }

            return coll;
        }

        /// <summary>
        /// Clears the cache
        /// </summary>
        /// <param name="context"></param>
        public static void ClearCache(HttpContext context)
        {
            context.Cache.Remove(AllLocationsKey);
        }
    }
}
